<?php
#                                                                                 
# author: Cody Sorgenfrey                                       
# (c)2013 South Hill Calvary Chapel                                               
#     

#TODO: handle _'s in form
                                                                            
include_once("../mysql/database_info.php");
include_once("../mysql/common.php");
include_once("../common.php");
connect_select_test("events");
$vars = explode("|row|", $_GET['vars']);
$id = array_shift($vars);
$addFee = array_pop($vars);
$paymentType = array_pop($vars);
$scholarship = array_pop($vars);
$paid = floatval(array_pop($vars));
$prices = mysql_fetch_array(mysql_query("SELECT * FROM `events` WHERE `id`='$id'"));
$grandTotal = calculatePrice(countPeople($id, $vars), $prices['costPerPerson'], $prices['costPerCouple'], $prices['maxCost'], $addFee);
if ($paid){
	$uri = "https://www.paypal.com/cgi-bin/webscr";
	$uri .= "?cmd=_xclick";
	$uri .= "&business=paypal%40southhillcalvary.org";
	$uri .= "&amount=".$grandTotal;
	$uri .= "&lc=US";
	$uri .= "&no_note=1";
	$uri .= "&no_shipping=2";
	$uri .= "&rm=1";
	$uri .= "&currency_code=USD";
	$uri .= "&page_style=SHCC";
	$uri .= "&item_name=SHCC+".urlencode($prices['title'])."+Registration";
	$uri .= "&item_number=SHCC-".urlencode($id);
	$uri .= "&notify_url=http://www.southhillcalvary.org/registration/backend.php";
	array_unshift($vars, $id);
	array_push($vars, $paymentType);
	array_push($vars, $scholarship);
	array_push($vars, $paid);
	$uri .= "&custom=".urlencode(implode("|row|", $vars));
	printf("<script type='text/javascript'>document.location = \"%s\"</script>", $uri);
	return 1;
} 
function calculatePrice($num, $cpp, $cpc, $mc, $fee){
	$price = 0;
	if (empty($cpp)) $cpp = 0;
	if (empty($cpc) && (!empty($cpp))) $cpc = $cpp*2; else $cpc = 0;
	if (empty($mc)) $mc = null; 
	if ($num % 2 == 0){
			$price = ($num / 2) * $cpc;
		} else {
			$price = (($num - 1)/2) * $cpc;
			if ($cpp != 0){
				$price += $cpp;
			} else {
				$price += $cpc;
			}
		}
		if ($mc != null){
			if ($price >= $mc){
				$price = $mc;
			}
		}
	if ($fee != "false"){	
		$price += (($price*.022)+.30);
	}
	return $price;
}
function countPeople($id, $vars){
	$query = mysql_query("SELECT * FROM `registrationForms` WHERE `event`='$id' LIMIT 1");
	$eventListeners = mysql_fetch_array($query);
	$indexOfListeners = null;
	$personCount = 0;
	for ($x=0;$x<count($eventListeners);$x++){
		if (!empty($eventListeners[$x."Type"])){
			$types[] = $eventListeners[$x."Type"];
			$names[] = $eventListeners[$x."Name"];
		}
	}
	for ($x=0;$x<count($types);$x++){
		if ((stristr($types[$x], "eventListener")) || (stristr($types[$x], "start multi"))){
			$indexOfListeners[] = $x;
		}
	}
	for ($x=0;$x<count($indexOfListeners);$x++){
		$personCount += count(explode(", ", $vars[$indexOfListeners[$x]]));
	}
	return $personCount;
}
$form = mysql_fetch_array(mysql_query("SELECT * FROM `registrationForms` WHERE `event`='$id'"));
for ($x=1; $x<=count($form);$x++){
	if (!empty($form[$x."Type"])){
		$types[] = $form[$x."Type"];
		$names[] = $form[$x."Name"];
		$placeholders[] = $form[$x."Placeholder"];
		if ($form[$x."Required"]){
			$required[] = "required";	
		} else{
			$required[] = "optional";
		}
		$newLine[] = $form[$x."newLine"];
	}
}
if (!table_exists("Registration_$id", "southhi9_shcc")){
	$newTable = "CREATE TABLE `Registration_$id` (
		  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,";
		  for ($x=0;$x<count($names);$x++){
			  $newTable.="`".$names[$x]."` text,";
		  }
		  $newTable.= "`paid` tinyint(1),";
		  $newTable.= "`scholarship` tinyint(1),";
		  $newTable.= "`paymentType` text,";
		  $newTable.= "`grandTotal` float,";
		  $newTable.="PRIMARY KEY (`id`)) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1";
	$test = mysql_query($newTable);
	if ($test){
		mail("codys@southhillcalvary.org", "Created new table", "Created Registration_$id");
	} else {
		mail("codys@southhillcalvary.org", "Failed to make table", "Failure to make Registration_$id, ".$newTable);
	}
}
//real query
$insert = "INSERT INTO `Registration_$id` VALUES(";
$insert.="'', ";
for ($x=0;$x<count($names);$x++){
	$insert.="'".$vars[$x]."', ";
}
$insert.="'".$paid."', ";
$insert.="'".$scholarship."', ";
$insert.="'".$paymentType."', ";
$insert.="'".$grandTotal."')";
$id = explode("-", $id);
$newId = $id[0];
if (mysql_query($insert)){
	mail("codys@southhillcalvary.org", "New Registration", "New registration for event $newId\r\nSee it at http://www.southhillcalvary.org/registration/?id=$newId\r\n \r\n".implode(", ", $vars));
} else {
	mail("codys@southhillcalvary.org", "Registration Failed", "Couldn't register ".$insert."\r\n \r\n".implode(", ", $vars));
}
printf("<script type='text/javascript'>document.location='/event/$newId&message=Thank+you+for+registering';</script>");
?>